package cn.com.stary1993.kite.captcha.store.impl;

import cn.com.stary1993.kite.captcha.store.CacheStore;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;

import java.util.Collections;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * redis实现的缓存
 *
 * @author stary1993
 */
public class RedisCacheStore implements CacheStore {

	private static final RedisScript<String> SCRIPT_GET_CACHE = new DefaultRedisScript<>(
			"local res = redis.call('get',KEYS[1])  if res == nil  then return nil  else  redis.call('del',KEYS[1]) return res end",
			String.class);

	protected StringRedisTemplate redisTemplate;

	public RedisCacheStore(StringRedisTemplate redisTemplate) {
		this.redisTemplate = redisTemplate;
	}

	@Override
	public Map<String, Object> getCache(String key) {
		String jsonData = redisTemplate.opsForValue().get(key);
		if (StrUtil.isEmpty(jsonData)) {
			return null;
		}
		return JSONUtil.toBean(jsonData, Map.class);
	}

	@Override
	public Map<String, Object> getAndRemoveCache(String key) {
		String json = redisTemplate.execute(SCRIPT_GET_CACHE, Collections.singletonList(key));
		if (StrUtil.isBlank(json)) {
			return null;
		}
		return JSONUtil.toBean(json, Map.class);
	}

	@Override
	public boolean setCache(String key, Map<String, Object> data, Long expire, TimeUnit timeUnit) {
		redisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(data), expire, timeUnit);
		return true;
	}

	/**
	 * 添加缓存数据
	 * @param key key
	 * @param data data
	 * @param expire 过期时间
	 * @param timeUnit 过期时间单位
	 * @return boolean
	 */
	@Override
	public boolean setCache(String key, String data, Long expire, TimeUnit timeUnit) {
		redisTemplate.opsForValue().set(key, data, expire, timeUnit);
		return true;
	}

}
